package com.example.clock.util;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.example.clock.cofig.DingtalkProperties;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author zmf
 * @Description:
 * @Date 2024-08-21 16:27
 * @Version V1.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */

@Component
public class DingTalkUtil {
    private static final String ToakenName = "DDAccessToken";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    DingtalkProperties dingtalkProperties;

    /**
     * 获取accseesToken
     */
    public String getAccessToken() {
        String accessToken = stringRedisTemplate.opsForValue().get(ToakenName);
        if (StringUtils.isEmpty(accessToken)) {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey( dingtalkProperties.getAppkey());
            request.setAppsecret(dingtalkProperties.getAppsecret());
            request.setHttpMethod("GET");
            OapiGettokenResponse response = null;
            try {
                response = client.execute(request);
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
            if (response.isSuccess()) {
                String responseAccessToken = response.getAccessToken();
                stringRedisTemplate.opsForValue().set(ToakenName, responseAccessToken, response.getExpiresIn() - 200, TimeUnit.SECONDS);
                return responseAccessToken;
            }
        } else {
            return accessToken;
        }
        return accessToken;
    }
}
